from rest_framework.viewsets import ModelViewSet
from django.db import transaction
from utils import response_error, response_ok
from utils.exception import CustomError


class CustomModelViewSet(ModelViewSet):

    def create(self, request, *args, **kwargs):
        try:
            with transaction.atomic():
                super(CustomModelViewSet, self).create(request, *args, **kwargs)
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            import traceback
            traceback.print_exc()
            return response_error(str(e))
        return response_ok()

    def update(self, request, *args, **kwargs):
        try:
            with transaction.atomic():
                super(CustomModelViewSet, self).update(request, *args, **kwargs)
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            return response_error(str(e))
        return response_ok()

    def destroy(self, request, *args, **kwargs):
        try:
            with transaction.atomic():
                super(CustomModelViewSet, self).destroy(request, *args, **kwargs)
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            return response_error(str(e))
        return response_ok()

    def retrieve(self, request, *args, **kwargs):
        try:
            instance = self.get_object()
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            return response_error(str(e))
        serializer = self.get_serializer(instance)
        return response_ok(serializer.data)

    def list(self, request, *args, **kwargs):

        print('---')
        try:
            queryset = self.filter_queryset(self.get_queryset())
            page = self.paginate_queryset(queryset)
            if page is not None:
                serializer = self.get_serializer(page, many=True)
                return self.get_paginated_response(serializer.data)
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            return response_error(str(e))
        serializer = self.get_serializer(queryset, many=True)
        return response_ok(serializer.data)
